from typing import Dict, Tuple
from cache.RedisClient import RedisMixin
import time, json
from database.db import session,User


class TextMessage(RedisMixin):
    content: str = ''
    form: str or Dict = ''
    to: str or Dict= ''
    send_time: int = 0
    is_read: bool = False
    key: str = ''

    def read(self):
        self.is_read = True

    def keys(self) -> Tuple:
        return (
            'content',
            'form',
            'to',
            'send_time',
            'is_read',
            'key'
        )

    def __getitem__(self, item) -> None:
        return getattr(self, item)

    def to_dict(self) -> Dict[str, object]:
        return dict(self)

    def __setitem__(self, key, value) -> None:
        setattr(self, key, value)

    @classmethod
    def from_json(cls, data: Dict[str, object]):
        return cls(data)

    def __init__(self, data: Dict[str, object] = None):
        super(TextMessage, self).__init__()

        if data:
            for i in data.keys():
                self[i] = data[i]
            self._gen_key()

    def save(self) -> str:
        '''
        :return: srt message id
        '''
        if not self.key:
            self._gen_key()

        self.client.set(self.key, json.dumps(self.to_dict()))

        return self.key

    def _gen_key(self, ):
        self.key = f'{self.to}_{self.form}_{int(time.time())}'


    def load_user(self):
        form = session.query(User).filter(User.username == self.form).first()
        to = session.query(User).filter(User.username == self.to).first()
        self.form = dict(form) if form else {}
        self.to = dict(to) if to else {}
